<template>
	<div class="edu-page-warp">
		<el-card shadow="never">
			<div class="edu-page-title" style="margin-bottom: 24px;">{{$t('teachers.teachingApplicationList')}}</div>
			<div class="edu-opertion-bar" style="margin-bottom: 16px;">
				<div class="float-left">
					<el-input v-model="queryForm.condition" :placeholder="$t('common.pla.teacherNameCode')" style="width:260px"
						@keyup.enter.native="onSubmit">
						<i class="el-icon-search" slot="suffix" style="margin-top:10px;cursor:pointer" @click="onSubmit"></i>
					</el-input>
				</div>
				<div class="float-right">
					<el-button type="primary" @click="down">{{$t("teachers.DownloadTeachingApplicationFrom")}}</el-button>
					<el-button type="primary" @click="showApplyDialog">{{$t('teachers.teachingApplication')}}</el-button>
				</div>
			</div>
			<el-table stripe :data="viewData" size="mini" width="100%" tooltip-effect="light">
        <edu-table-column :label="$t('message.order')" type="index" sortable align="center" width="60"/>
				<edu-table-column prop="teacherCode" :label="$t('courseArrange.preArrangeLog.code')"/>
				<edu-table-column prop="name" :label="$t('teachers.teacherName')"/>
				<!--<edu-table-column prop="engName" :label="$t('message.nameEn')"/>-->
				<edu-table-column prop="applyTime" :label="$t('teachers.applyTime')"/>
				<edu-table-column prop="applyType" :label="$t('teachers.applicationType')">
					<template slot-scope="props">{{getApplyType(props.row.applyType)}}</template>
				</edu-table-column>
				<edu-table-column prop="status" :label="$t('message.status')">
					<template slot-scope="props">
            <el-tag v-if="props.row.status==2" type="info" size="mini">{{ $t('message.checkPending') }}</el-tag>
						<el-tag v-if="props.row.status==3" type="info" size="mini">{{ $t('message.checking') }}</el-tag>
						<el-tag v-if="props.row.status==4" type="success" size="mini">{{ $t('message.pass') }}</el-tag>
						<el-tag v-if="props.row.status==0" type="danger" size="mini">{{ $t('message.refuse') }}</el-tag>
					</template>
				</edu-table-column>
			</el-table>
			<el-row>
				<el-col>
					<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryForm.pageNum_"
						:page-sizes="[20,50,100,500,1000]" :page-size="queryForm.pageSize_" layout="total, sizes, prev, pager, next, jumper"
						:total="queryForm.total_" style="float:right;margin-top:10px"></el-pagination>
				</el-col>
			</el-row>
		</el-card>
		<el-dialog :title="$t('teachers.applicationAuthorized')" width="700px"
			:visible.sync="showDialog" v-drag-dialog @close="handleClose">
			<el-form label-position="right" :model="postForm" label-width="140px" :rules="rules" ref="postForm"
				label-suffix="：">
				<el-row>
					<el-col :span="24">
						<el-form-item :label="$t('courseSummary.applicant')" prop="id">
							<el-select v-model="postForm.id" remote filterable :remote-method="selectTeacher" :placeholder="$t('teachers.inputNameOrNoSearch')"
								clearable style="width: 50%" v-clearreadonly>
								<el-option v-for="item in options.applyTeachers" :key="item.value" :label="item.label" :value="item.value"></el-option>
								<!-- <i class="el-icon-arrow-down"  slot="prefix"></i> -->
								<i class="el-icon-arrow-down" slot="suffix"></i>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item :label="$t('teachers.applicationTeaching')" prop="apporoveType">
							<el-select v-model="postForm.apporoveType" style="width:50%" :disabled="this.typeDisabled">
								<el-option v-for="item in options.types" :key="item.value" :label="item.label" :value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item :label="$t('teachers.subjectMajorCommittee')" prop="subjectMajorCode">
							<el-select v-model="postForm.subjectMajorCode" filterable style="width:90%"  @change="changeSubMajor" v-clearreadonly>
								<el-option
									v-for="item in options.subjectMajorCode"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item :label="$t('teachers.appointApprover')" prop="appointUserCode">
							<el-select v-model="postForm.appointUserCode" style="width:90%">
								<el-option
									v-for="item in options.appointUserCode"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item :label="$t('teachers.applicationReason')" prop="reason">
							<el-input type="textarea" v-model="postForm.reason" rows="3" style="width:90%" maxlength="500"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<span slot="footer">
				<el-button @click="cancelApply">{{$t("message.cancel")}}</el-button>
				<el-button @click="saveApply" type="primary">{{$t("message.confirm")}}</el-button>
			</span>
		</el-dialog>
	</div>
</template>
<script>
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
import {
	qualificationList,
	getQualificationList,
	applyQualification,
  getSubjectMajorByUser,
  getSubjectMajorRole,
	getApplyFile
} from "common/src/api/resource/teachers";
import mixin from 'common/src/mixins/index';
export default {
	name: "",
	mixins: [mixin],
	data() {
		return {
			queryForm: {
				condition: "",
				pageNum_: 1,
				pageSize_: 20,
				total_: 0
			},
			postForm: {
				id: null,
				apporoveType: null,
				reason: null,
        applyFaculty:null,
				subjectMajorCode:null,
				appointUserCode:null
			},
      typeDisabled:true,
			currentManageDptId:'',
      subjectMajors:[],
			options: {
        faculty:[],
				types: [],
				applyTeachers: [],
				subjectMajorCode:[],
				appointUserCode:[]
			},
			rules: {
				id: [
					{
						required: true,
						message: this.$t("teachers.plsChooseApplicant"),
						trigger: "change"
					}
				],
				apporoveType: [
					{
						required: true,
						message: this.$t("teachers.plsChooseApplyTeaching"),
						trigger: "change"
					}
				],
				reason: [
					{
						required: true,
						message: this.$t("teachers.plsChooseApplicationReason"),
						trigger: "change"
					}
				],
        /*applyFaculty: [
          {
            required: true,
            message: this.$t("teachers.plsChooseApplyFaculty"),
            trigger: "change"
          }
        ],*/
				subjectMajorCode: [
					{
						required: true,
						message: this.$t("teachers.mustChooseSubjectMajorCommittee"),
						trigger: "change"
					}
				],
				appointUserCode: [
					{
						required: true,
						message: this.$t("teachers.mustAppointApprover"),
						trigger: "change"
					}
				]
			},
			showDialog: false,
			viewData: []
		};
	},
	mounted: function() {
    /*let user = this.$store.state.session.user || JSON.parse(localStorage.getItem("user"));
    if (user && user.currentManageDptId) {
      this.currentManageDptId = user.currentManageDptId;
		}*/
	//let user = this.global.currentUser;
	//let depts=user.manageDptIds.filter(dept_=>dept_!=1);
      //console.info("depts:" + depts);
	//let defaultDeptIds=depts.length>0?depts[0]:null;
    this.currentManageDptId = this.global.projectId;
    console.info("currentManageDptId:" + this.currentManageDptId);
		this.init();
	},
	methods: {
		init() {
      const data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["X_YX"]
      };
      queryDic(data).then(res => {
        if (res.code === 200) {
            UTILS.fillSelect({faculty: "X_YX"}, res.data, this.options);
        }
      });

      let underTeachQual = {label: this.$t("teachers.underTeachQual"), value: 1};
      let postTeachQual = {label: this.$t("teachers.postTeachQual"), value: 2};
      let postTeachQualOnjob = {label: this.$t("teachers.postTeachQualOnjob"), value: 3};

      if(this.global.isAnyTeacher){
          this.currentManageDptId = '';
      }

			switch(this.currentManageDptId){
        /*case '1':
          this.options.types.push(underTeachQual);
          this.postForm.apporoveType = 1;
        this.typeDisabled = true;*/
				case '2':
					this.options.types.push(postTeachQual);
				  this.postForm.apporoveType = 2;
				  this.typeDisabled = true;
				  break;
				case '4':
					this.options.types.push(postTeachQualOnjob);
          this.postForm.apporoveType = 3;
          this.typeDisabled = true;
				  break;
				default:
          //this.options.types.push(underTeachQual,postTeachQual,postTeachQualOnjob);
          this.options.types.push(postTeachQual,postTeachQualOnjob);
          this.typeDisabled = false;
			}
			this.onSubmit();
			//查询专业学科委员会
      getSubjectMajorByUser([]).then(res =>{
				if (res.code == 200 && res.data.length > 0) {
          for (const item of res.data) {
              this.options.subjectMajorCode.push({
                  label: item.subjectMajorName + '('+ item.faculty +')',
                  value: item.subjectMajorCode
              });
          }
          this.subjectMajors = res.data;
        }
			});
		},
		onSubmit() {
			this.getDataList();
		},
		getDataList(isFirstPage = true) {
			if (isFirstPage) {
				this.queryForm.pageNum_ = 1;
			}
			getQualificationList(this.queryForm).then(res => {
				if (res.code == 200) {
					this.viewData = res.data.list;
					this.queryForm.total_ = res.data.total_;
				}
			});
		},
		handleSizeChange(val) {
			this.queryForm.pageSize_ = val;
			this.getDataList();
		},
		handleCurrentChange(val) {
			this.queryForm.pageNum_ = val;
			this.getDataList(false);
		},
		showApplyDialog() {
			this.showDialog = true;
			this.selectTeacher("");
			this.$refs.postForm.clearValidate();
			if(this.options.faculty.length === 1){
			    this.postForm.faculty = this.options.faculty[0].value;
      }
		},
		handleClose(){
			this.postForm.id = null;
      this.postForm.applyFaculty=null;
			this.postForm.subjectMajorCode=null;
			this.postForm.appointUserCode=null;
			this.options.appointUserCode=[];
			this.postForm.reason = null;
			this.options.applyTeachers.length = 0;
		},
		cancelApply() {
			this.showDialog = false;
		},
		saveApply() {
			this.$refs.postForm.validate(valid => {
				if (!valid) {
					return;
				}
				applyQualification(this.postForm).then(res => {
					if (res.code == 200) {
						this.showDialog = false;
						this.onSubmit();
					}
				});
			});
		},
		getApplyType(val) {
			switch(val){
				case 1:
					return this.$t("teachers.underTeachQual");
				case 2:
					return this.$t("teachers.postTeachQual");
				case 3:
					return this.$t("teachers.postTeachQualOnjob");
				default:
					return '';
			}
		},
		selectTeacher(query) {
			qualificationList(query).then(res => {
				if (res.code == 200) {
					this.options.applyTeachers = res.data.map(c => {
						return {
							label: c.name + "(" + c.code + ")",
							value: c.id
						};
					});
				}
			});
		},
		down() {
			getApplyFile().then(res => {
				if (res.code == 200) {
					window.location.href = "/api/commonservice/obsfile/downloadfile?objectkey=" +
							res.data;
					/* window.open(
						"/api/commonservice/obsfile/downloadfile?objectkey=" +
							res.data
					); */

					/* this.showUploadDialog = false; */
				} else {
					throw response.code;
				}
			});
		},
		changeSubMajor(val){
			this.postForm.appointUserCode = null;
            this.options.appointUserCode = [];
            if(val){
                //获取学委会所属学院
                this.subjectMajors.forEach((item) => {
                    if (item.subjectMajorCode == val) {
                        this.postForm.applyFaculty = item.faculty;
                    }
                });
                //获取审核人信息
                getSubjectMajorRole(val).then(res =>{
                    if (res.code == 200 && res.data.length > 0) {
                        for (const item of res.data) {
                            this.options.appointUserCode.push({
                                label: item.userName+'('+item.userCode+')',
                                value: item.userCode
                            });
                        }
                    }
                });
            }
		}
	}
};
</script>
<style lang="scss" scoped>
</style>
